package com.gelpag.base.business.common;

import been.UserInfo;
import com.gelpag.base.tools.CommonUtil;
import entity.Const;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class CommonBase {

    @Autowired
    RedisTemplate redisTemplate;
    static RedisTemplate staticRedisTemplate;

    @Autowired
    CommonService commonService;
    static CommonService staticCommonService;

    //在容器启动的时候加载这个方法，目的是给staticRedis赋值
    @PostConstruct
    public void init() {
        staticRedisTemplate = redisTemplate;
        staticCommonService = commonService;
    }

    //通过token获取用户信息
    public static UserInfo getUserInFromToken(String token) throws Exception {

        try {
            Claims claims = Jwts.parser().setSigningKey(Const.JWT_KEY).parseClaimsJws(token.replace(Const.PRE_TOKEN,"")).getBody();
            UserInfo userInfo = new UserInfo();
            userInfo.setUser_id((String) claims.get("user_id"));
            userInfo.setUser_name((String) claims.get("user_name"));
            userInfo.setUser_type((String) claims.get("user_type"));
            userInfo.setUnit_ids((List<String>) claims.get("unit_ids"));
            userInfo.setUnit_id((String) claims.get("unit_id"));

            userInfo.setUser_level(CommonUtil.getRoleRange(staticCommonService.getUserRoleList(userInfo.getUser_id())));
            return userInfo;
        } catch (Exception e) {
            //如果token过时返回null
            e.printStackTrace();
            return null;
        }
    }
}
